import grace from "../../utils/grace.js"
grace.page({
      data: {
            carts: [], //购物车列表
            selected: [], //选择的商品编号
            total: { //总价
                  is_auth: true //手否需要绑定手机
            },
            selectAllStatus: true, // 全选状态，默认全选
      },
      onLoad: function(options) {
            this.$bus.$on("update_cart_event", (data) => {
                  // this.loadData();
                  // this.calcTotal();
            });
            this.$bus.$on("update_phone_event", (data) => {
                  this.$data.total.is_auth = true;
                  this.calcTotal();
            });
            this.dialog = this.selectComponent("#dialog_phone");
      },
      openDetail: function(e) {
            let goods_id = e.currentTarget.dataset.goods;
            wx.navigateTo({
                  url: '../product_details/product_details?goods_id=' + goods_id,
            })
      },
      onPullDownRefresh: function() {
            this.loadData();
      },
      onShow: function() {
            wx.showNavigationBarLoading();
            this.loadData();
      },
      loadData: function() {
            this.$http.get('api/cart/list', {}).then((res) => {
                  this.$data.carts = this.updateItemChecked(res.list, true);
                  this.calcTotal();
            });
      },
      calcTotal: function() {
            let cart_vals = this.$data.selected.join(',');
            this.$http.get('api/cart/statistics', {
                  cart_vals: cart_vals
            }).then((res) => {
                  this.$data.total = res;
                  this.$data['is_auth'] = res['is_auth'];
            })
      },
      openSubmit: function() {
            if (this.$data.selected.length == 0) {
                  this.toast('请先选择商品!');
                  return;
            }
            var cart_vals = this.$data.selected.join(',');
            wx.navigateTo({
                  url: '../cart_pay/cart_pay?cart_vals=' + cart_vals
            })
      },
      // 增加数量
      addCount: function(e) {
            const cart_id = e.currentTarget.dataset.cartid;
            const index = e.currentTarget.dataset.index;

            let carts = this.data.carts;
            let num = carts[index].goods_number;
            num = parseInt(num) + 1;
            this.updateGoods(cart_id, num, index);

            carts[index].goods_number = num;
            this.$data.carts = carts;
      },
      // 减少数量
      minusCount: function(e) {
            const cart_id = e.currentTarget.dataset.cartid;
            const index = e.currentTarget.dataset.index;
            let carts = this.data.carts;
            let num = carts[index].goods_number;
            if (parseInt(num) > 1) {
                  num = parseInt(num) - 1;
                  carts[index].goods_number = num;
                  this.$data.carts = carts;

                  this.updateGoods(cart_id, num);
            }
      },
      /**
       * 购物车编号，数量，下标
       */
      updateGoods: function(cart_id, goods_number, index) {
            this.$http.post('api/cart/update_goods', {
                  cart_id: cart_id,
                  goods_number: goods_number
            }).then((res) => {
                  // let carts = this.$data.carts;
                  // carts[index].goods_number = num;
                  // this.$data.carts = carts;

                  this.calcTotal();
            }).catch(err => {
                  if (err.status == 400) {
                        var res = JSON.parse(err.engine.response);
                        let carts = this.$data.carts;
                        carts[index]['goods_stock'] = res.goods_stock;
                        carts[index]['goods_number'] = res.goods_stock;
                        carts[index]['goods_warn'] = true;
                        this.$data.carts = carts;
                        this.toast(res.message);
                  }
            });
      },
      //商品的选择监听
      selectedChange: function(e) {
            this.$data.selected = e.detail.value;

            if (e.detail.value.length == this.$data.carts.length) {
                  this.$data.selectAllStatus = true;
            }

            if (this.$data.selected.length == 0) {
                  this.$data.total['total_amount'] = 0;
                  this.$data.total['goods_number'] = 0;
            } else {
                  this.calcTotal();
            }
      },
      //全选
      selectAllChange(e) {
            let isChecked = e.detail.value.length > 0;
            let carts = this.updateItemChecked(this.$data.carts, isChecked);
            this.$data = {
                  selectAllStatus: isChecked,
                  carts: carts
            }
            if (isChecked) {
                  this.calcTotal();
            } else {
                  this.$data.selected = [];
                  this.$data.total['total_amount'] = 0;
                  this.$data.total['goods_number'] = 0;
            }

      },
      updateItemChecked: function(carts, isChecked) {
            let select_id = new Array();
            for (var i = 0; i < carts.length; ++i) {
                  var item = carts[i];
                  if (item['checked'] == undefined) {
                        item['checked'] = true;
                  }
                  item['checked'] = isChecked;
                  select_id.push(item['cart_id']);
            }
            this.$data.selected = select_id;
            return carts;
      },
      itemChange: function(e) {
            const index = e.currentTarget.dataset.index;
            let carts = this.data.carts;
            carts[index].checked = !carts[index].checked;
            this.$data.carts = carts;
            if (carts[index].checked == false) {
                  this.$data.selectAllStatus = false;
            }
      },
      deletedCart: function() {
            if (this.$data.selected.length == 0) {
                  this.toast('请先选择商品!');
                  return;
            }
            let that = this;
            wx.showModal({
                  title: '提示',
                  content: '确定要删除选中的商品吗？',
                  success: function(res) {
                        if (res.confirm) {
                              let cart_vals = that.$data.selected.join(',');
                              that.$http.post('api/cart/delete_goods', {
                                    cart_vals: cart_vals
                              }).then((res) => {
                                    that.loadData();
                                    that.calcTotal();
                              });
                        }
                  }
            })

      },

      showDialog() {
            this.dialog.showDialog();
      },
      hideDialog() {
            this.dialog.hideDialog();
      },
})